import { memo, useState, useEffect } from 'react';
import {
  Toast,
  Steps,
  Popup,
  Divider,
  Tabs,
  Selector,
  Empty,
} from 'antd-mobile';
import axios from 'axios';

const { Step } = Steps;
export const OrderCourse = () => {
  const [orderCourse, setOrderCourse] = useState([]); // 预约课程列表
  // const [flag, setFlag] = useState(false); //控制预约---预约成功文字切换
  const [visible1, setVisible1] = useState(false); // popup弹框
  const [cardList, setCardList] = useState([]); // 渲染预约对应消费卡
  // const [curItemCourse, setCurItemCourse] = useState({}); //预约成功当前课程预约情况切换为---预约成功
  const [courseTime, setCourseTime] = useState([]); // 渲染课程可预约时间
  // const [selectTime, setSelectTime] = useState(''); // 选中的预约时间
  const [selectCardFlag, setSelectCardFlag] = useState(''); // 选中消费卡ID---添加高亮
  const [courseObj, setCourseObj] = useState({}); // 确认预约课程

  // 确认预约
  const onConfirm = () => {
    setVisible1(false);
    const obj = orderCourse.find((item: any) => item.orgId === courseObj.orgId);
    const newArr = orderCourse.map((item) => {
      if (item.orgId === obj.orgId) {
        item.flag = !item.flag;
      }
      return item;
    });
    setOrderCourse(newArr);
    Toast.show({
      icon: 'success',
      content: '预约成功',
    });
  };
  // 请求预约课程列表
  const getCourseList = async () => {
    const studentID = localStorage.getItem('StudentID');
    if (studentID) {
      const { data } = await axios.get(
        `http://127.0.0.1:3000/getReservationList?id=${
          JSON.stringify(studentID)}`,
      );
      if (data.code === 200) {
        await setOrderCourse(data.data);
      }
    }
  };
  useEffect(() => {
    getCourseList();
    // 根据传入的星期数 获取具体的年月日
    // function getYearMonthDayForDayOfWeek(dayOfWeek:any) {
    //   // 创建一个表示当前日期的 Date 对象
    //   var currentDate = new Date();

    //   // 计算当前日期与目标星期之间的天数差值
    //   var timeDiff = dayOfWeek - currentDate.getDay();
    //   if (timeDiff < 0) {
    //     timeDiff += 7;  // 如果目标星期已经过去，则计算到下一个对应星期的天数差
    //   }

    //   // 使用 setDate 方法设置日期为当前日期加上差值
    //   var targetDate = new Date(currentDate.getTime() + timeDiff * 24 * 60 * 60 * 1000);

    //   // 提取年、月、日
    //   var year = targetDate.getFullYear();
    //   var month = targetDate.getMonth() + 1; // 月份从 0 开始计数，需要加 1
    //   var day = targetDate.getDate();

    //   // 返回结果
    //   return {
    //     year: year,
    //     month: month,
    //     day: day
    //   };
    // }

    // 传入要计算的星期几（0 表示星期日，1 表示星期一，以此类推）
    // var targetDayOfWeek = "0"; // 假设要获取星期三对应的日期
    // var result = getYearMonthDayForDayOfWeek(targetDayOfWeek);
    // eslint-disable-next-line max-len
    // console.log("下一个星期", targetDayOfWeek, "对应的年月日：", result.year, "年", result.month, "月", result.day, "日");
  }, []);
  // 点击预约
  const reservation = async (obj: any) => {
    setVisible1(true); // 显示popup
    const { data } = await axios.get(
      `http://127.0.0.1:3000/getCardList?id=${obj.productId}`,
    );
    if (data.code === 200) {
      const arr: any = [];
      data.data.forEach((item: any) => {
        arr.push({
          orgId: obj.orgId,
          cardId: item.id,
          type: item.name, // 卡类型  次卡---时长卡
          name: obj.desc, // 卡名
          count: obj.quantity + item.validityDay, // 剩余次数
          flag: obj.flag,
        });
      });
      setCourseObj({ flag: arr.flag });
      setCardList(arr);
    }
    const arr: any = [];
    // 查询课程可预约的时间
    const data2 = await axios.get(
      `http://127.0.0.1:3000/getCourseTime?id=${obj.productId}`,
    );
    const reducibleTime = JSON.parse(data2.data.data.reducibleTime);
    reducibleTime.forEach((item: any) => {
      if (item.orderTime.length) {
        arr.push(item);
      }
    });
    setCourseTime(arr);
  };
  // 预约周几
  const selectWeek = (obj: string) => {
    setCourseObj({ ...courseObj, week: obj });
  };
  // 点击预约具体时间
  const changeTime = (str: any, key: any) => {
    console.log(key, 'key');
    setCourseObj({ ...courseObj, time: str });
  };

  // 选中卡片
  const selectCard = (obj: any) => {
    const idx = cardList.findIndex((item: any) => item.cardId === obj.cardId);
    if (idx !== -1) {
      setSelectCardFlag(cardList[idx].cardId);
    }
    setCourseObj({ ...courseObj, ...obj });
  };
  return (
    <div className="container">
      {/* 如果有课程直接渲染 */}
      {orderCourse.length ? (
        <Steps direction="vertical">
          {orderCourse.map((item: any, idx: any) => (
            <Step
              // eslint-disable-next-line react/no-array-index-key
              key={idx}
              title={item.name}
              status="finish"
              description={(
                <div
                  key={item.id}
                  style={{
                    display: 'flex',
                    justifyContent: 'space-around',
                    backgroundColor: 'white',
                    padding: '5px 0',
                  }}
                >
                  <div>
                    <img
                      style={{ width: '80px', height: '50px' }}
                      src={item.coverUrl}
                      alt=""
                    />
                  </div>
                  <div>
                    <p>{item.desc}</p>
                  </div>
                  <div style={{ lineHeight: '30px' }}>
                    {item.flag === false ? (
                      <p
                        onClick={() => {
                          reservation(item);
                        }}
                        style={{ color: '#12B19B' }}
                      >
                        预约
                      </p>
                    ) : (
                      <p style={{ color: 'red' }}>预约成功</p>
                    )}
                  </div>
                </div>
              )}
            />
          ))}

          <Step title="没有更多了" status="wait" />
        </Steps>
      ) : (
        <Empty description="暂无可预约课程" />
      )}

      {/* 底部弹出框 */}
      <Popup
        visible={visible1}
        onMaskClick={() => {
          setVisible1(false);
        }}
        onClose={() => {
          setVisible1(false);
        }}
        bodyStyle={{ height: '45vh' }}
      >
        <Divider>请选择预约时间</Divider>

        <Tabs
          defaultActiveKey="1"
          onChange={(key) => {
            selectWeek(key);
          }}
        >
          {courseTime.map((item: any, idx) => (
            <Tabs.Tab title={item.week} key={idx}>
              <div
                onClick={() => {
                  console.log(1111);
                }}
              >
                <Selector
                  options={item.orderTime}
                  onChange={(key, extend: any) => {
                    changeTime(extend.items[0].label, key);
                  }}
                />
                <Divider>选择消费卡</Divider>
                {cardList.map((item: any, idx) => (
                  <div
                    key={idx}
                    onClick={() => {
                      selectCard(item);
                    }}
                    style={{
                      border: `${
                        selectCardFlag === item.cardId
                          ? '1px solid #0A8E81'
                          : ''
                      }`,
                    }}
                  >
                    <div
                      style={{
                        height: '50px',
                        width: '100%',
                        background: '#F2F2F2',
                        padding: '0 0 3px 0',
                      }}
                    >
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          padding: '5px 8px 0 5px',
                        }}
                      >
                        <div>
                          <span
                            style={{
                              fontSize: '12px',
                              border: '1px solid #0A8E81',
                              color: '#0A8E81',
                              fontWeight: 'bold',
                            }}
                          >
                            {item.type}
                          </span>
                          <span
                            style={{
                              marginLeft: '10px',
                              color: 'black',
                              fontFamily: '楷体',
                              fontWeight: 'bold',
                            }}
                          >
                            {item.name}
                          </span>
                          <p style={{ color: 'orange' }}>
                            剩余
                            {item.count}
                            次
                          </p>
                        </div>
                        <div style={{ fontFamily: '楷体' }}>
                          有效期至:2023-12-30
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
                <button
                  style={{
                    marginTop: '20px',
                    border: '0',
                    borderRadius: '5px',
                    width: '100%',
                    height: '40px',
                    background: '#0A8E81',
                    color: 'white',
                  }}
                  onClick={() => {
                    onConfirm();
                  }}
                >
                  确认预约
                </button>
              </div>
            </Tabs.Tab>
          ))}
        </Tabs>
      </Popup>
    </div>
  );
};

export default memo(OrderCourse);
